package io.lvdaxian.mybatis11.executor.resultset;

import io.lvdaxian.mybatis11.executor.Executor;
import io.lvdaxian.mybatis11.executor.result.DefaultResultContext;
import io.lvdaxian.mybatis11.executor.result.DefaultResultHandler;
import io.lvdaxian.mybatis11.mapping.BoundSql;
import io.lvdaxian.mybatis11.mapping.MappedStatement;
import io.lvdaxian.mybatis11.mapping.ResultMap;
import io.lvdaxian.mybatis11.mapping.ResultMapping;
import io.lvdaxian.mybatis11.reflection.MetaClass;
import io.lvdaxian.mybatis11.reflection.MetaObject;
import io.lvdaxian.mybatis11.reflection.factory.ObjectFactory;
import io.lvdaxian.mybatis11.session.Configuration;
import io.lvdaxian.mybatis11.session.ResultHandler;
import io.lvdaxian.mybatis11.session.RowBounds;
import io.lvdaxian.mybatis11.type.TypeHandler;
import io.lvdaxian.mybatis11.type.TypeHandlerRegistry;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 默认的结果集 处理
 *
 * @author lihh
 */
public class DefaultResultSetHandler implements ResultSetHandler {
  
  private final Configuration configuration;
  private final MappedStatement mappedStatement;
  private final RowBounds rowBounds;
  private final ResultHandler resultHandler;
  private final BoundSql boundSql;
  private final TypeHandlerRegistry typeHandlerRegistry;
  private final ObjectFactory objectFactory;
  
  public DefaultResultSetHandler(Executor executor, MappedStatement mappedStatement, ResultHandler resultHandler, RowBounds rowBounds, BoundSql boundSql) {
    this.configuration = mappedStatement.getConfiguration();
    this.rowBounds = rowBounds;
    this.boundSql = boundSql;
    this.mappedStatement = mappedStatement;
    this.resultHandler = resultHandler;
    this.objectFactory = configuration.getObjectFactory();
    this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
  }
  
  /**
   * 这里是 处理结果集 的方法
   *
   * @param stmt 查询得到的 statement
   * @return
   * @throws SQLException
   * @author lihh
   */
  @Override
  @SuppressWarnings("unchecked")
  public List<Object> handleResultSets(Statement stmt) throws SQLException {
    // 表示 复数个 结果集
    final List<Object> multipleResults = new ArrayList<>();
    
    int resultSetCount = 0;
    // 这里 将结果集 包装
    ResultSetWrapper rsw = new ResultSetWrapper(stmt.getResultSet(), configuration);
    
    List<ResultMap> resultMaps = mappedStatement.getResultMaps();
    while (rsw != null && resultMaps.size() > resultSetCount) {
      ResultMap resultMap = resultMaps.get(resultSetCount);
      // 从这里尝试 处理结果集
      handleResultSet(rsw, resultMap, multipleResults, null);
      rsw = getNextResultSet(stmt);
      resultSetCount++;
    }
    
    return multipleResults.size() == 1 ? (List<Object>) multipleResults.get(0) : multipleResults;
  }
  
  private ResultSetWrapper getNextResultSet(Statement stmt) throws SQLException {
    // Making this method tolerant of bad JDBC drivers
    try {
      if (stmt.getConnection().getMetaData().supportsMultipleResultSets()) {
        // Crazy Standard JDBC way of determining if there are more results
        if (!((!stmt.getMoreResults()) && (stmt.getUpdateCount() == -1))) {
          ResultSet rs = stmt.getResultSet();
          return rs != null ? new ResultSetWrapper(rs, configuration) : null;
        }
      }
    } catch (Exception ignore) {
      // Intentionally ignored.
    }
    return null;
  }
  
  private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults, ResultMapping parentMapping) throws SQLException {
    if (resultHandler == null) {
      // 1. 新创建结果处理器
      DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
      // 2. 封装数据
      handleRowValuesForSimpleResultMap(rsw, resultMap, defaultResultHandler, rowBounds, null);
      // 3. 保存结果
      multipleResults.add(defaultResultHandler.getResultList());
    }
  }
  
  private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
    // 默认结果 上下文
    DefaultResultContext resultContext = new DefaultResultContext();
    // 说明还是存在下一个值的
    while (resultContext.getResultCount() < rowBounds.getLimit() && rsw.getResultSet().next()) {
      // 从这里 转换 数据
      Object rowValue = getRowValue(rsw, resultMap);
      callResultHandler(resultHandler, resultContext, rowValue);
    }
  }
  
  private void callResultHandler(ResultHandler resultHandler, DefaultResultContext resultContext, Object rowValue) {
    resultContext.nextResultObject(rowValue);
    resultHandler.handleResult(resultContext);
  }
  
  /**
   * 获取一行的值
   */
  private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap) throws SQLException {
    // 根据返回类型，实例化对象
    Object resultObject = createResultObject(rsw, resultMap, null);
    if (resultObject != null && !typeHandlerRegistry.hasTypeHandler(resultMap.getType())) {
      // 元 信息对象
      final MetaObject metaObject = configuration.newMetaObject(resultObject);
      applyAutomaticMappings(rsw, resultMap, metaObject, null);
    }
    return resultObject;
  }
  
  private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, String columnPrefix) throws SQLException {
    final List<Class<?>> constructorArgTypes = new ArrayList<>();
    final List<Object> constructorArgs = new ArrayList<>();
    return createResultObject(rsw, resultMap, constructorArgTypes, constructorArgs, columnPrefix);
  }
  
  /**
   * 创建结果
   */
  private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, List<Class<?>> constructorArgTypes, List<Object> constructorArgs, String columnPrefix) throws SQLException {
    // 表示 返回类型
    final Class<?> resultType = resultMap.getType();
    // 返回类型的 元数据
    final MetaClass metaType = MetaClass.forClass(resultType);
    // 如果是接口 || 存在默认的构造函数的话
    if (resultType.isInterface() || metaType.hasDefaultConstructor()) {
      // 普通的Bean对象类型 直接生成一个对象 这里是 根据 class 生成 对象
      return objectFactory.create(resultType);
    }
    throw new RuntimeException("Do not know how to create an instance of " + resultType);
  }
  
  private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {
    final List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
    boolean foundValues = false;
    // 这里遍历 列名称
    for (String columnName : unmappedColumnNames) {
      String propertyName = columnName;
      if (columnPrefix != null && !columnPrefix.isEmpty()) {
        // When columnPrefix is specified,ignore columns without the prefix.
        if (columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
          propertyName = columnName.substring(columnPrefix.length());
        } else {
          continue;
        }
      }
      // 寻找列名称 确认列名称 是否真的存在
      final String property = metaObject.findProperty(propertyName, false);
      // 是否存在 setter 方法
      if (property != null && metaObject.hasSetter(property)) {
        // 拿到类型
        final Class<?> propertyType = metaObject.getSetterType(property);
        // 是否存在类型处理器
        if (typeHandlerRegistry.hasTypeHandler(propertyType)) {
          // 拿到类型处理器
          final TypeHandler<?> typeHandler = rsw.getTypeHandler(propertyType, columnName);
          // 使用 TypeHandler 取得结果
          final Object value = typeHandler.getResult(rsw.getResultSet(), columnName);
          if (value != null) {
            foundValues = true;
          }
          if (value != null || !propertyType.isPrimitive()) {
            // 通过反射工具类设置属性值
            metaObject.setValue(property, value);
          }
        }
      }
    }
    return foundValues;
  }
  
}
